import React, { useState, useEffect } from 'react';
import styles from './index.less';
import { Form, Input, Button, Checkbox, message } from 'antd';
import { portalLogin } from '@/services/login/login';
import {
  setToken,
  setUserInfo,
  removeToken,
  removeUserInfo,
  getUserInfo,
  getToken,
} from '@/utils/storage';
import { connect } from 'umi';
import { history } from '@@/core/history';
import { getIsLogin, scrollToTop } from '@/utils/util';

const NormalLoginForm: React.FC = (props) => {
  const { isLogin, dispatch }: any = props;
  const [loginName, setLoginName] = useState(getUserInfo()?.companyName || '');
  const [login, setLogin] = useState<boolean>(false);
  const [refresh, setRefresh] = useState<boolean>(false);
  const hasToken = getToken();
  useEffect(() => {
    setLogin(isLogin);
  }, [isLogin]);
  const onFinish = async (values: any) => {
    const { userAccount, password } = values;
    await portalLogin({
      userAccount,
      password,
    }).then((resp) => {
      message.success('登录成功');
      dispatch({
        type: 'login/fetchIsLogin',
        payload: true,
      });
      setLoginName(resp.results.user.companyName);
      const response: any = resp.results;
      if (response.user) {
        setUserInfo(response.user);
      }
      if (response?.token) {
        setToken(response.token);
      }
      setRefresh(!refresh);
    });
  };
  const signOut = () => {
    try {
      message.success('退出成功');
      removeToken();
      removeUserInfo();
      dispatch({
        type: 'login/fetchIsLogin',
        payload: false,
      });
      setRefresh(!refresh);
    } catch (error) {
      message.error('退出失败');
    }
  };
  const goToPersonalCenter = () => {
    if (!getIsLogin()) {
      message.error('请先登录');
      history.push({ pathname: '/' });
      scrollToTop();
      return;
    }
    try {
      history.push({ pathname: '/personalCenter' });
    } catch (error) {
      message.error('请联系管理员');
    }
  };
  const goToRegister = () => {
    try {
      history.push({ pathname: '/userRegister' });
    } catch (error) {
      message.error('请联系管理员');
    }
  };
  return (
    <div className={styles.container}>
      <div className={styles.formList}>
        {!login || !hasToken ? (
          <Form
            name="normal_login"
            className="login-form"
            initialValues={{ remember: true }}
            onFinish={onFinish}
          >
            <h3>用户登录</h3>
            <Form.Item name="userAccount" rules={[{ required: true, message: '请输入用户名' }]}>
              <Input placeholder="请输入用户名" />
            </Form.Item>
            <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" className="login-form-button">
                登录
              </Button>
            </Form.Item>
            <Form.Item>
              <Button
                onClick={goToRegister}
                type="primary"
                className="register-form-button"
                style={{
                  backgroundColor: 'rgba(43, 87, 158, 0.26)',
                }}
              >
                注册
              </Button>
            </Form.Item>
            <Form.Item>
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox>记住账户</Checkbox>
              </Form.Item>
              {/* <a className="login-form-forgot" href=""> */}
              {/*  忘记密码 */}
              {/* </a> */}
            </Form.Item>
          </Form>
        ) : (
          <div className={styles.loginSucceed}>
            <div className={styles.loginIn}>
              欢迎<span className={styles.userName}>{loginName}</span>登录
            </div>
            <div className={styles.loginInTitle}>
              {process.env.SYSTEM === 'policy'
                ? '武汉经济技术开发区政策兑现服务平台'
                : '武汉经济技术开发区政企直通车服务平台'}
            </div>
            <div
              className={styles.loginCenter}
              style={{ cursor: 'pointer' }}
              onClick={goToPersonalCenter}
            >
              进入个人中心
            </div>
            <div className={styles.signOut} onClick={signOut}>
              退出
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default connect(({ login }: any) => ({
  isLogin: login.isLogin,
}))(NormalLoginForm);
